// 链接数据库
const mysql=require('mysql');
const config = require('./defaultConfig');

// mysql连接
// 1、创建线程池（链接数据库的准备工作）
let pool=mysql.createPool({
    host:config.dataBase.HOST,
    user:config.dataBase.USERNAME,
    password:config.dataBase.PASSWORD,
    database:config.dataBase.DATABASE,
    port:config.dataBase.PORT
})

// 2、连接线程池，做sql语句查找
let allService={
    query:function(sql,values){
        return new Promise((resolve, reject) => {
            pool.getConnection(function(err,connection){//链接数据库
                if(err){//链接失败
                    reject(err);
                }else{//链接成功
                    // 增删改查
                    connection.query(sql,values,(err,rows)=>{//执行sql语句
                        if(err){
                            reject(err);
                        }else{
                            resolve(rows);
                        }
                        connection.release();//释放连接
                    });
                }
            })
        })

    }
}

// 调用allService

// 用户登录
let userLogin=function(username,password){
    let _sql=`select * from users where username='${username}' and userpwd='${password}';`;
    return allService.query(_sql);
}

// 查找用户
let findUser=function(username){
    let _sql=`select * from users where username='${username}';`;
    return allService.query(_sql);
}

// 用户注册
let insertUser=function(value){
    let _sql=`insert into users set username=?,userpwd=?,nickname=?;`;
    return allService.query(_sql,value);
}

// 根据类型查找对应的文章列表
let findNoteListByType=function(type){
    let _sql=`select * from note where note_type='${type}';`
    return allService.query(_sql)
}

// 根据id，查找对应的文章详情
let findNoteDetailById=function(id){
    let _sql=`select * from note where id='${id}';`;
    return allService.query(_sql)

}

// 添加日记
let insertNote=function(value){
    let _sql=`insert into note set useId=?,title=?,note_type=?,note_content=?,c_time=?,m_time=?,head_img=?,nickname=?;`;
    return allService.query(_sql, value);

}

module.exports={
    userLogin,
    findUser,
    insertUser,
    findNoteListByType,
    findNoteDetailById,
    insertNote
};